package com.isoftstone.activity;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

import com.isoftstone.util.RUtil;

public class ImagePagerActivity extends FragmentActivity {
	private static final String STATE_POSITION = "STATE_POSITION";
	public static final String EXTRA_IMAGE_INDEX = "image_index";
	public static final String EXTRA_IMAGE_URLS = "image_urls";

	private HackyViewPager mPager;
	private int pagerPosition;
	private TextView indicator;
	private TextView save;
	private int position = 0;
	private String IMAGES_DIR = Environment.getExternalStorageDirectory()
			.getAbsolutePath() + "/isoftstone";
	private String IMAGE_FILE_NAME = "image.jpg";
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 0:
				Toast.makeText(
						ImagePagerActivity.this,
						"图片保存路径为:" + IMAGES_DIR + "/"
								+ String.valueOf(System.currentTimeMillis())
								+ IMAGE_FILE_NAME, Toast.LENGTH_SHORT).show();
				break;

			default:
				break;
			}
		};
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//		setContentView(R.layout.plugin_image_detail_pager);
		setContentView(RUtil.instance.getLayout("plugin_image_detail_pager"));

		pagerPosition = getIntent().getIntExtra(EXTRA_IMAGE_INDEX, 0);
		final ArrayList<String> urls = getIntent().getStringArrayListExtra(
				EXTRA_IMAGE_URLS);

		mPager = (HackyViewPager) findViewById(RUtil.instance.getId("pager"));
		save = (TextView) findViewById(RUtil.instance.getId("save"));
		save.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				new Thread() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						super.run();
						downloadImage(urls.get(position), IMAGES_DIR + "/"
								+ String.valueOf(System.currentTimeMillis())
								+ IMAGE_FILE_NAME);
					}
				}.start();

			}
		});

		ImagePagerAdapter mAdapter = new ImagePagerAdapter(
				getSupportFragmentManager(), urls);
		mPager.setAdapter(mAdapter);
		indicator = (TextView) findViewById(RUtil.instance.getId("indicator"));

		CharSequence text = getString(RUtil.instance.getString("plugin_viewpager_indicator"), 1, mPager
				.getAdapter().getCount());
		indicator.setText(text);
		// 更新下标
		mPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageScrollStateChanged(int arg0) {
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}

			@Override
			public void onPageSelected(int arg0) {
				CharSequence text = getString(RUtil.instance.getString("plugin_viewpager_indicator"),
						arg0 + 1, mPager.getAdapter().getCount());
				position = arg0;
				indicator.setText(text);
			}

		});
		if (savedInstanceState != null) {
			pagerPosition = savedInstanceState.getInt(STATE_POSITION);
		}

		mPager.setCurrentItem(pagerPosition);
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		outState.putInt(STATE_POSITION, mPager.getCurrentItem());
	}

	private class ImagePagerAdapter extends FragmentStatePagerAdapter {

		public ArrayList<String> fileList;

		public ImagePagerAdapter(FragmentManager fm, ArrayList<String> fileList) {
			super(fm);
			this.fileList = fileList;
		}

		@Override
		public int getCount() {
			return fileList == null ? 0 : fileList.size();
		}

		@Override
		public Fragment getItem(int position) {
			String url = fileList.get(position);
			return ImageDetailFragment.newInstance(url);
		}

	}

	private void downloadImage(String imageUrl, String path) {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			Log.d("TAG", "monted sdcard");
		} else {
			Log.d("TAG", "has no sdcard");
		}
		File dirFile = new File(path.substring(0, path.lastIndexOf("/")));
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}
		HttpURLConnection con = null;
		FileOutputStream fos = null;
		BufferedOutputStream bos = null;
		BufferedInputStream bis = null;
		File imageFile = null;
		try {
			URL url = new URL(imageUrl);
			con = (HttpURLConnection) url.openConnection();
			con.getResponseCode();
			con.setConnectTimeout(5 * 1000);
			con.setReadTimeout(15 * 1000);
			bis = new BufferedInputStream(con.getInputStream());
			imageFile = new File(path);
			fos = new FileOutputStream(imageFile);
			bos = new BufferedOutputStream(fos);
			byte[] b = new byte[1024];
			int length;
			while ((length = bis.read(b)) != -1) {
				bos.write(b, 0, length);
				bos.flush();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (bis != null) {
					bis.close();
				}
				if (bos != null) {
					bos.close();
				}
				if (con != null) {
					con.disconnect();
				}
				handler.sendEmptyMessage(0);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}